<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Tracker - 专业股票分析工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        success: '#52C41A',
                        danger: '#FF4D4F',
                        warning: '#FAAD14',
                        neutral: '#8C8C8C',
                        dark: '#1F2329',
                        light: '#F5F5F5',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            .backdrop-blur {
                backdrop-filter: blur(8px);
            }
        }
    </style>

    <style>
        body {
            font-family: 'Inter', sans-serif;
            overflow-x: hidden;
        }

        /* 悬浮球样式 */
        .floating-ball {
            position: fixed;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #165DFF, #36CFC9);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            cursor: move;
            box-shadow: 0 4px 15px rgba(22, 93, 255, 0.4);
            z-index: 9998;
            transition: all 0.3s ease;
            user-select: none;
            right: 30px;
            bottom: 30px;
        }

        .floating-ball:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(22, 93, 255, 0.5);
        }

        /* 设置面板样式 */
        .settings-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            z-index: 9998;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .settings-overlay.active {
            opacity: 1;
        }

        .settings-panel {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.95);
            background-color: #FFFFFF;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            width: 90%;
            max-width: 1000px;
            max-height: 90vh;
            overflow-y: auto;
            z-index: 9999;
            opacity: 0;
            transition: all 0.3s ease;
        }

        .settings-panel.active {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }

        .settings-content {
            padding: 24px;
        }

        .settings-content h3 {
            color: #1F2329;
            font-size: 22px;
            font-weight: 600;
            margin: 0 0 20px 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* 股票输入区域 */
        .stock-input {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 24px;
            align-items: center;
        }

        #stockCode {
            flex: 1;
            min-width: 200px;
            padding: 12px 16px;
            border: 1px solid #E5E6EB;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s ease;
        }

        #stockCode:focus {
            outline: none;
            border-color: #165DFF;
            box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
        }

        .stock-input button {
            padding: 12px 20px;
            border-radius: 8px;
            border: none;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        /* 已在HTML中内联样式 */

        /* 已在HTML中内联样式 */

        #kimiAiBtn {
            background-color: #F7F8FA;
            color: #1F2329;
        }

        #kimiAiBtn:hover {
            background-color: #E5E6EB;
        }

        #importBtn {
            background-color: #F7F8FA;
            color: #1F2329;
        }

        #importBtn:hover {
            background-color: #E5E6EB;
        }

        /* 股票摘要 */
        .stock-summary {
            display: flex;
            gap: 20px;
            margin-top: 12px;
            width: 100%;
        }

        .summary-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .summary-label {
            color: #8C8C8C;
            font-size: 14px;
        }

        .summary-value {
            color: #1F2329;
            font-size: 14px;
            font-weight: 500;
        }

        .summary-value.profit {
            color: #52C41A;
        }

        .summary-value.loss {
            color: #FF4D4F;
        }

        /* 刷新状态 */
        .refresh-status {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            font-size: 13px;
            color: #8C8C8C;
        }

        .market-status.trading {
            color: #52C41A;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .market-status.trading::before {
            content: '';
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: #52C41A;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0.5;
            }

            100% {
                opacity: 1;
            }
        }

        /* 股票列表 */
        #stockList {
            margin-top: 16px;
        }

        .stock-list-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 16px;
        }

        .stock-list-item {
            background-color: #FFFFFF;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            padding: 16px;
            transition: all 0.3s ease;
            border: 1px solid #F0F0F0;
        }

        .stock-list-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
        }

        .stock-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }

        .stock-name {
            display: flex;
            flex-direction: column;
        }

        .stock-name strong {
            color: #1F2329;
            font-size: 16px;
            font-weight: 600;
        }

        .stock-code {
            color: #8C8C8C;
            font-size: 12px;
            margin-top: 4px;
        }

        .stock-actions {
            display: flex;
            gap: 8px;
        }

        .action-link {
            color: #8C8C8C;
            font-size: 12px;
            text-decoration: none;
            cursor: pointer;
            transition: color 0.2s ease;
        }

        .action-link:hover {
            color: #165DFF;
        }

        .detail-btn:hover {
            color: #52C41A;
        }

        .settings-btn:hover {
            color: #FAAD14;
        }

        .delete-btn:hover {
            color: #FF4D4F;
        }

        .quant-btn:hover {
            color: #36CFC9;
        }

        /* 股票价格 */
        .stock-price {
            font-size: 18px;
            font-weight: 600;
            color: #1F2329;
            margin-bottom: 12px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
        }

        .stock-price.up {
            color: #52C41A;
        }

        .stock-price.down {
            color: #FF4D4F;
        }

        .stock-change {
            font-size: 14px;
            font-weight: 500;
        }

        .quant-indicator {
            font-size: 12px;
            padding: 3px 8px;
            border-radius: 12px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .quant-indicator.buy {
            background-color: rgba(82, 196, 26, 0.1);
            color: #52C41A;
        }

        .quant-indicator.sell {
            background-color: rgba(255, 77, 79, 0.1);
            color: #FF4D4F;
        }

        .quant-indicator.hold {
            background-color: rgba(250, 173, 20, 0.1);
            color: #FAAD14;
        }

        /* 股票详情 */
        .stock-details {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 12px;
        }

        .detail-item {
            font-size: 12px;
            color: #8C8C8C;
            padding: 3px 0;
        }

        .profit-info {
            font-size: 14px;
            font-weight: 500;
            padding-top: 8px;
            border-top: 1px dashed #F0F0F0;
        }

        .profit-info.up {
            color: #52C41A;
        }

        .profit-info.down {
            color: #FF4D4F;
        }

        /* 股票设置面板 */
        .stock-settings-panel {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            z-index: 10000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .stock-settings-panel.active {
            opacity: 1;
            visibility: visible;
        }

        .settings-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .form-group label {
            font-size: 14px;
            color: #1F2329;
            font-weight: 500;
        }

        .form-group input {
            padding: 12px 16px;
            border: 1px solid #E5E6EB;
            border-radius: 8px;
            font-size: 14px;
        }

        .form-group input:focus {
            outline: none;
            border-color: #165DFF;
            box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
        }

        .shares-input {
            display: flex;
            align-items: center;
        }

        .shares-input input {
            flex: 1;
            border-right: none;
            border-radius: 8px 0 0 8px;
        }

        .unit {
            padding: 12px 16px;
            border: 1px solid #E5E6EB;
            border-left: none;
            border-radius: 0 8px 8px 0;
            font-size: 14px;
            color: #8C8C8C;
            background-color: #F7F8FA;
        }

        .shares-tip {
            font-size: 12px;
            color: #8C8C8C;
            margin-top: -4px;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            margin-top: 10px;
        }

        .form-actions button {
            flex: 1;
            padding: 12px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
        }

        .save-btn {
            background-color: #165DFF;
            color: white;
            border: none;
        }

        .save-btn:hover {
            background-color: #0E4CD1;
        }

        .cancel-btn {
            background-color: #F7F8FA;
            color: #1F2329;
            border: 1px solid #E5E6EB;
        }

        /* 批量导入面板 */
        .import-panel {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #FFFFFF;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            width: 90%;
            max-width: 500px;
            z-index: 10000;
            padding: 24px;
        }

        .import-panel h3 {
            color: #1F2329;
            font-size: 18px;
            font-weight: 600;
            margin: 0 0 16px 0;
            padding-bottom: 16px;
            border-bottom: 1px solid #F0F0F0;
        }

        .import-content {
            margin-bottom: 20px;
        }

        .import-textarea {
            width: 100%;
            min-height: 150px;
            padding: 12px 16px;
            border: 1px solid #E5E6EB;
            border-radius: 8px;
            font-size: 14px;
            resize: vertical;
        }

        .import-textarea:focus {
            outline: none;
            border-color: #165DFF;
        }

        .import-actions {
            display: flex;
            gap: 12px;
        }

        .import-actions button {
            flex: 1;
            padding: 12px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
        }

        .import-btn {
            background-color: #165DFF;
            color: white;
            border: none;
        }

        /* 量化分析面板 */
        .quantitative-advice-panel {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            z-index: 10000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .quantitative-advice-panel.active {
            opacity: 1;
            visibility: visible;
        }

        .advice-content {
            background-color: #FFFFFF;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            width: 90%;
            max-width: 700px;
            max-height: 80vh;
            overflow-y: auto;
            padding: 24px;
        }

        .advice-content h3 {
            color: #1F2329;
            font-size: 18px;
            font-weight: 600;
            margin: 0 0 20px 0;
            padding-bottom: 16px;
            border-bottom: 1px solid #F0F0F0;
        }

        .advice-action {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .advice-action.buy {
            background-color: rgba(82, 196, 26, 0.1);
            border-left: 4px solid #52C41A;
        }

        .advice-action.sell {
            background-color: rgba(255, 77, 79, 0.1);
            border-left: 4px solid #FF4D4F;
        }

        .advice-action.hold {
            background-color: rgba(250, 173, 20, 0.1);
            border-left: 4px solid #FAAD14;
        }

        .action-icon {
            font-size: 24px;
        }

        .action-text {
            font-size: 18px;
            font-weight: 600;
            flex: 1;
        }

        .advice-action.buy .action-text {
            color: #52C41A;
        }

        .advice-action.sell .action-text {
            color: #FF4D4F;
        }

        .advice-action.hold .action-text {
            color: #FAAD14;
        }

        .confidence {
            font-size: 14px;
            color: #8C8C8C;
            background-color: rgba(255, 255, 255, 0.7);
            padding: 4px 10px;
            border-radius: 12px;
        }

        .advice-message {
            color: #1F2329;
            font-size: 15px;
            margin-bottom: 20px;
            line-height: 1.5;
        }

        .advice-reasons {
            margin-bottom: 20px;
        }

        .advice-reasons h4 {
            color: #1F2329;
            font-size: 16px;
            font-weight: 600;
            margin: 0 0 12px 0;
        }

        .advice-reasons ul {
            list-style-type: disc;
            padding-left: 20px;
            margin: 0;
        }

        .advice-reasons li {
            color: #4E5969;
            font-size: 14px;
            margin-bottom: 8px;
            line-height: 1.5;
        }

        .advice-details {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 12px;
            padding: 16px;
            background-color: #F7F8FA;
            border-radius: 8px;
            margin-bottom: 24px;
        }

        .advice-actions {
            display: flex;
            justify-content: flex-end;
        }

        .close-btn {
            padding: 10px 20px;
            background-color: #165DFF;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
        }

        .close-btn:hover {
            background-color: #0E4CD1;
        }

        /* 股票提示框 */
        .stock-suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background-color: #FFFFFF;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
            z-index: 100;
            margin-top: -1px;
            border: 1px solid #E5E6EB;
            border-top: none;
        }

        .suggestion-item {
            padding: 10px 16px;
            cursor: pointer;
            transition: background-color 0.2s ease;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .suggestion-item:hover,
        .suggestion-item.active {
            background-color: #F7F8FA;
        }

        .suggestion-code {
            color: #165DFF;
            font-size: 14px;
            font-weight: 500;
        }

        .suggestion-name {
            color: #8C8C8C;
            font-size: 14px;
        }

        /* 股票提醒 */
        .stock-alert {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #FFFFFF;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
            padding: 16px;
            display: flex;
            align-items: center;
            gap: 12px;
            z-index: 9999;
            min-width: 300px;
            max-width: 400px;
            animation: slideIn 0.3s ease;
            border-left: 4px solid;
        }

        .stock-alert.profit {
            border-color: #52C41A;
        }

        .stock-alert.loss {
            border-color: #FF4D4F;
        }

        .stock-alert.info {
            border-color: #165DFF;
        }

        .alert-icon {
            font-size: 20px;
        }

        .alert-message {
            flex: 1;
            color: #1F2329;
            font-size: 14px;
            line-height: 1.5;
        }

        .alert-close {
            background: none;
            border: none;
            color: #8C8C8C;
            font-size: 16px;
            cursor: pointer;
        }

        .stock-alert.fade-out {
            animation: fadeOut 0.3s ease forwards;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes fadeOut {
            from {
                opacity: 1;
            }

            to {
                opacity: 0;
                transform: translateY(-10px);
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .settings-panel {
                width: 95%;
                max-height: 95vh;
            }

            .stock-list-container {
                grid-template-columns: 1fr;
            }

            .stock-input {
                flex-direction: column;
            }

            #stockCode,
            .stock-input button {
                width: 100%;
            }
        }
    </style>
</head>

<body class="bg-gray-50 font-inter text-dark">
    <!-- 页面主内容 -->
    <div class="min-h-screen flex flex-col">
        <!-- 顶部导航 -->
        <header class="bg-white shadow-sm sticky top-0 z-10">
            <div class="container mx-auto px-4 py-4 flex justify-between items-center">
                <div class="flex items-center gap-2">
                    <i class="fa fa-line-chart text-primary text-2xl"></i>
                    <h1 class="text-xl font-bold text-dark">Stock Tracker</h1>
                </div>
                <div class="flex items-center gap-4">
                    <button id="themeToggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                        <i class="fa fa-moon-o text-neutral"></i>
                    </button>
                    <button id="helpBtn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                        <i class="fa fa-question text-neutral"></i>
                    </button>
                </div>
            </div>
        </header>

        <!-- 主要内容区 -->
        <main class="flex-1 container mx-auto px-4 py-8">
            <div class="bg-white rounded-xl shadow p-6 mb-8">
                <h2 class="text-xl font-semibold mb-4">欢迎使用 Stock Tracker</h2>
                <p class="text-gray-600 mb-6">这是一款专业的股票分析工具，帮助您跟踪和分析股票市场动态。</p>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-gray-50 rounded-lg p-5 transition-transform hover:transform hover:scale-105">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                                <i class="fa fa-list text-primary"></i>
                            </div>
                            <h3 class="font-medium">股票跟踪</h3>
                        </div>
                        <p class="text-sm text-gray-600">添加并跟踪您关注的股票，实时获取价格变动和市场数据。</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg p-5 transition-transform hover:transform hover:scale-105">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center">
                                <i class="fa fa-calculator text-secondary"></i>
                            </div>
                            <h3 class="font-medium">量化分析</h3>
                        </div>
                        <p class="text-sm text-gray-600">通过技术指标和算法分析，为您提供专业的股票买卖建议。</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg p-5 transition-transform hover:transform hover:scale-105">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-full bg-success/10 flex items-center justify-center">
                                <i class="fa fa-bell text-success"></i>
                            </div>
                            <h3 class="font-medium">智能提醒</h3>
                        </div>
                        <p class="text-sm text-gray-600">设置止盈止损点，当股票达到目标价格时自动提醒。</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow p-6">
                <h2 class="text-xl font-semibold mb-4">市场概览</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h3 class="text-base font-medium mb-4">主要指数</h3>
                        <div class="space-y-4">
                            <div
                                class="flex justify-between items-center p-3 border border-gray-200 rounded-lg hover:shadow-md transition-shadow">
                                <div>
                                    <div class="font-medium">上证指数</div>
                                    <div class="text-sm text-gray-500">000001</div>
                                </div>
                                <div class="text-right">
                                    <div class="font-medium text-success">3,218.43</div>
                                    <div class="text-sm text-success">+0.72%</div>
                                </div>
                            </div>
                            <div
                                class="flex justify-between items-center p-3 border border-gray-200 rounded-lg hover:shadow-md transition-shadow">
                                <div>
                                    <div class="font-medium">深证成指</div>
                                    <div class="text-sm text-gray-500">399001</div>
                                </div>
                                <div class="text-right">
                                    <div class="font-medium text-success">11,243.98</div>
                                    <div class="text-sm text-success">+1.25%</div>
                                </div>
                            </div>
                            <div
                                class="flex justify-between items-center p-3 border border-gray-200 rounded-lg hover:shadow-md transition-shadow">
                                <div>
                                    <div class="font-medium">创业板指</div>
                                    <div class="text-sm text-gray-500">399006</div>
                                </div>
                                <div class="text-right">
                                    <div class="font-medium text-danger">2,345.67</div>
                                    <div class="text-sm text-danger">-0.48%</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <h3 class="text-base font-medium mb-4">市场情绪</h3>
                        <div class="h-64">
                            <canvas id="marketSentimentChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="bg-white border-t border-gray-200 py-6">
            <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
                <p>© 2023 Stock Tracker. 保留所有权利。</p>
                <p class="mt-2">免责声明：本工具提供的信息仅供参考，不构成任何投资建议。</p>
            </div>
        </footer>
    </div>

    <!-- JavaScript 代码 -->
    <script>
        // 初始化市场情绪图表
        document.addEventListener('DOMContentLoaded', function () {
            const ctx = document.getElementById('marketSentimentChart').getContext('2d');
            const chart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['看涨', '看跌', '中性'],
                    datasets: [{
                        data: [42, 28, 30],
                        backgroundColor: [
                            '#52C41A',
                            '#FF4D4F',
                            '#8C8C8C'
                        ],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        },
                        title: {
                            display: true,
                            text: '投资者情绪分布'
                        }
                    },
                    cutout: '60%'
                }
            });
        });

        // 创建悬浮球
        function createFloatingBall() {
            const ball = document.createElement('div');
            ball.className = 'floating-ball';
            ball.innerHTML = 'ST';
            document.body.appendChild(ball);

            // 添加点击事件
            ball.addEventListener('click', (e) => {
                e.stopPropagation(); // 阻止事件冒泡
                const settingsPanel = document.querySelector('.settings-panel');
                if (settingsPanel) {
                    closeSettings();
                } else {
                    openSettings();
                }
            });

            // 添加拖拽功能
            let isDragging = false;
            let currentX;
            let currentY;
            let initialX;
            let initialY;
            let xOffset = 0;
            let yOffset = 0;

            ball.addEventListener('mousedown', dragStart);

            function dragStart(e) {
                initialX = e.clientX - xOffset;
                initialY = e.clientY - yOffset;

                if (e.target === ball) {
                    isDragging = true;
                    ball.classList.add('dragging');
                }
            }

            document.addEventListener('mousemove', drag);
            document.addEventListener('mouseup', dragEnd);

            function drag(e) {
                if (isDragging) {
                    e.preventDefault();
                    currentX = e.clientX - initialX;
                    currentY = e.clientY - initialY;

                    xOffset = currentX;
                    yOffset = currentY;

                    setTranslate(currentX, currentY, ball);
                }
            }

            function setTranslate(xPos, yPos, el) {
                el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
            }

            function dragEnd() {
                initialX = currentX;
                initialY = currentY;
                isDragging = false;
                ball.classList.remove('dragging');
            }

            return ball;
        }

        // 创建股票信息面板
        function createStockPanel() {
            const panel = document.createElement('div');
            panel.className = 'stock-panel';

            // 添加设置按钮
            const settingsBtn = document.createElement('button');
            settingsBtn.className = 'settings-btn';
            settingsBtn.innerHTML = '设置';
            settingsBtn.onclick = showSettings;

            // 添加刷新按钮
            const refreshBtn = document.createElement('button');
            refreshBtn.className = 'refresh-btn';
            refreshBtn.innerHTML = '刷新';
            refreshBtn.onclick = () => refreshStockData();

            panel.appendChild(settingsBtn);
            panel.appendChild(refreshBtn);

            return panel;
        }

        // 创建股票代码提示列表
        let stockSuggestions = [];
        let currentSuggestionIndex = -1;

        // 获取股票代码建议
        async function getStockSuggestions(input) {
            if (!input) return [];

            // 这里使用新浪财经的API获取股票列表
            try {
                const response = await fetch('https://hq.sinajs.cn/list=sh000001,sz399001,sh600000,sh600036,sz000858,sz000651,sh601318,sz002594,sh601899,sz000002');
                const text = await response.text();
                const stocks = text.split('\n').filter(line => line.includes('var hq_str_'));

                return stocks
                    .map(line => {
                        const code = line.match(/hq_str_(sh|sz)\d{6}/)[0].replace('hq_str_', '');
                        const name = line.split('=')[1].split(',')[0].replace(/"/g, '');
                        return { code, name };
                    })
                    .filter(stock =>
                        stock.code.toLowerCase().includes(input.toLowerCase()) ||
                        stock.name.includes(input)
                    )
                    .slice(0, 5); // 最多显示5个建议
            } catch (error) {
                console.error('获取股票建议失败:', error);
                return [];
            }
        }

        // 显示股票代码建议
        function showSuggestions(suggestions) {
            const input = document.getElementById('stockCode');
            let suggestionList = document.getElementById('stockSuggestions');

            if (!suggestionList) {
                suggestionList = document.createElement('div');
                suggestionList.id = 'stockSuggestions';
                suggestionList.className = 'stock-suggestions';
                input.parentNode.appendChild(suggestionList);
            }

            if (suggestions.length === 0) {
                document.getElementById('stockSuggestions')?.remove();
                return;
            }

            suggestionList.innerHTML = suggestions.map((stock, index) => `
                <div class="suggestion-item ${index === currentSuggestionIndex ? 'active' : ''}" 
                     onclick="selectSuggestion('${stock.code}')">
                    <span class="suggestion-code">${stock.code}</span>
                    <span class="suggestion-name">${stock.name}</span>
                </div>
            `).join('');
        }

        // 选择建议的股票代码
        function selectSuggestion(code) {
            const input = document.getElementById('stockCode');
            input.value = code;
            input.focus();
            document.getElementById('stockSuggestions')?.remove();
            currentSuggestionIndex = -1;
        }

        // 处理键盘导航
        function handleKeyNavigation(e) {
            const suggestions = document.querySelectorAll('.suggestion-item');
            if (suggestions.length === 0) return;

            switch (e.key) {
                case 'ArrowDown':
                    e.preventDefault();
                    currentSuggestionIndex = (currentSuggestionIndex + 1) % suggestions.length;
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    currentSuggestionIndex = (currentSuggestionIndex - 1 + suggestions.length) % suggestions.length;
                    break;
                case 'Enter':
                    e.preventDefault();
                    if (currentSuggestionIndex >= 0) {
                        const code = suggestions[currentSuggestionIndex].querySelector('.suggestion-code').textContent;
                        selectSuggestion(code);
                    } else {
                        addStock();
                    }
                    break;
                case 'Escape':
                    document.getElementById('stockSuggestions')?.remove();
                    currentSuggestionIndex = -1;
                    break;
            }

            showSuggestions(stockSuggestions);
        }

        // 批量导入股票
        async function importStocks() {
            const textarea = document.createElement('textarea');
            textarea.className = 'import-textarea';
            textarea.placeholder = '请输入股票代码，每行一个\n例如：\n600000\n000858';

            const importPanel = document.createElement('div');
            importPanel.className = 'import-panel';
            importPanel.innerHTML = `
                <h3>批量导入股票</h3>
                <div class="import-content"></div>
                <div class="import-actions">
                    <button class="cancel-btn" onclick="closeImportPanel()">取消</button>
                    <button class="import-btn" onclick="confirmImport()">导入</button>
                </div>
            `;

            importPanel.querySelector('.import-content').appendChild(textarea);
            document.body.appendChild(importPanel);
            textarea.focus();
        }

        // 确认导入
        async function confirmImport() {
            const textarea = document.querySelector('.import-textarea');
            const codes = textarea.value
                .split('\n')
                .map(code => code.trim().toLowerCase())
                .filter(code => code && validateStockCode(code));

            if (codes.length === 0) {
                alert('没有有效的股票代码');
                return;
            }

            const { stocks } = await getStoredStocks();
            const newStocks = [...new Set([...stocks, ...codes])];

            // 模拟chrome.storage.local.set
            localStorage.setItem('stocks', JSON.stringify(newStocks));
            loadStockList();
            refreshStockData();
            closeImportPanel();

            // 显示成功提示
            showAlert(`成功导入 ${codes.length} 只股票`, 'info');
        }

        // 关闭导入面板
        function closeImportPanel() {
            const importPanel = document.querySelector('.import-panel');
            if (importPanel) {
                importPanel.remove();
            }
        }

        // 验证股票代码格式
        function validateStockCode(code) {
            // 只验证6位数字
            const pattern = /^\d{6}$/;
            return pattern.test(code);
        }

        // 获取股票前缀
        function getStockPrefix(code) {
            // 上海主板：600、601、603、605开头
            // 上海科创板：688开头
            // 深圳主板：000开头
            // 深圳创业板：300、301开头
            // 深圳中小板：002开头
            const prefix = code.substring(0, 3);
            if (['600', '601', '603', '605', '688'].includes(prefix)) {
                return 'sh';
            } else if (['000', '002', '300', '301'].includes(prefix)) {
                return 'sz';
            }
            return '';
        }

        // 获取股票名称
        async function getStockName(code) {
            try {
                // 转换股票代码格式为东方财富格式
                const secid = code.startsWith('sh') ? `1.${code.slice(2)}` : `0.${code.slice(2)}`;
                const response = await fetch(`https://push2.eastmoney.com/api/qt/stock/get?secid=${secid}&fields=f58,f57`);
                const data = await response.json();

                if (!data.data || !data.data.f58) {
                    throw new Error('获取股票名称失败');
                }

                return data.data.f58;
            } catch (error) {
                console.error('获取股票名称失败:', error);
                return code;
            }
        }

        // 获取存储的股票列表
        async function getStoredStocks() {
            try {
                // 模拟chrome.storage.local.get
                const stocksJson = localStorage.getItem('stocks');
                const stockSettingsJson = localStorage.getItem('stockSettings');

                return {
                    stocks: stocksJson ? JSON.parse(stocksJson) : ['sh000001', 'sz399001'],
                    settings: stockSettingsJson ? JSON.parse(stockSettingsJson) : {}
                };
            } catch (error) {
                console.error('获取存储数据失败:', error);
                // 返回默认值
                return {
                    stocks: ['sh000001', 'sz399001'],
                    settings: {}
                };
            }
        }

        // 获取股票数据
        async function fetchStockData(stockCodes) {
            try {
                const promises = stockCodes.map(async code => {
                    console.log(code, 'code')
                    try {
                        // 转换股票代码格式为东方财富格式
                        const secid = code.startsWith('sh') ? `1.${code.slice(2)}` : `0.${code.slice(2)}`;
                        const response = await fetch(`https://push2.eastmoney.com/api/qt/stock/get?secid=${secid}&fields=f59,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292`);
                        const data = await response.json();

                        if (!data.data) {
                            throw new Error('数据格式错误');
                        }

                        const quote = data.data;
                        const settings = await getStockSettings(code);
                        const currentPrice = quote.f43 / 100; // 当前价
                        const preClose = quote.f60 / 100; // 昨收
                        const change = currentPrice - preClose; // 涨跌额
                        const changePercent = (change / preClose * 100).toFixed(2); // 涨跌幅

                        // 计算持仓盈亏
                        const holdingAmount = settings.costPrice * (settings.shares || 0); // 持仓金额
                        const marketValue = currentPrice * (settings.shares || 0); // 市值
                        const profitAmount = marketValue - holdingAmount; // 盈亏金额
                        const profitPercent = holdingAmount ? ((marketValue / holdingAmount - 1) * 100).toFixed(2) : '0.00'; // 盈亏比例

                        return {
                            code,
                            name: quote.f58,
                            price: currentPrice,
                            change,
                            changePercent,
                            volume: quote.f47 * 100, // 成交量
                            amount: quote.f48 * 10000, // 成交额
                            costPrice: settings.costPrice || 0,
                            shares: settings.shares || 0,
                            holdingAmount,
                            marketValue,
                            profitAmount,
                            profitPercent
                        };
                    } catch (error) {
                        console.error(`获取股票 ${code} 数据失败:`, error);
                        return {
                            code,
                            name: '获取失败',
                            price: 0,
                            change: 0,
                            changePercent: '0.00',
                            volume: 0,
                            amount: 0,
                            costPrice: 0,
                            shares: 0,
                            holdingAmount: 0,
                            marketValue: 0,
                            profitAmount: 0,
                            profitPercent: '0.00'
                        };
                    }
                });
                return await Promise.all(promises);
            } catch (error) {
                console.error('获取股票数据失败:', error);
                return [];
            }
        }

        // 保存股票设置
        async function saveStockSettings(code, settings) {
            const { stocks, settings: currentSettings } = await getStoredStocks();
            currentSettings[code] = settings;
            // 模拟chrome.storage.local.set
            localStorage.setItem('stockSettings', JSON.stringify(currentSettings));
        }

        // 获取股票设置
        async function getStockSettings(code) {
            const { settings } = await getStoredStocks();
            return settings[code] || {
                costPrice: 0,
                profitTarget: 0,
                lossTarget: 0,
                soundEnabled: true,
                alertFrequency: 'once', // once, every
                lastAlertTime: 0
            };
        }

        // 创建股票设置面板
        function createStockSettingsPanel(code, name) {
            const settingsPanel = document.createElement('div');
            settingsPanel.className = 'stock-settings-panel active';
            settingsPanel.innerHTML = `
                <div class="settings-content">
                    <h3>${name} (${code})</h3>
                    <div class="settings-form">
                        <div class="form-group">
                            <label>成本价：</label>
                            <input type="number" id="costPrice" step="0.01" min="0" placeholder="请输入成本价">
                        </div>
                        <div class="form-group">
                            <label>持仓数量：</label>
                            <div class="shares-input">
                                <input type="number" id="shares" step="1" min="0" placeholder="请输入持仓数量">
                                <span class="unit">手</span>
                            </div>
                            <div class="shares-tip">1手 = 100股</div>
                        </div>
                        <div class="form-actions">
                            <button class="save-btn" data-code="${code}">保存</button>
                            <button class="cancel-btn">取消</button>
                        </div>
                    </div>
                </div>
            `;

            // 添加事件监听器
            const saveBtn = settingsPanel.querySelector('.save-btn');
            const cancelBtn = settingsPanel.querySelector('.cancel-btn');

            saveBtn.addEventListener('click', () => {
                const costPrice = parseFloat(settingsPanel.querySelector('#costPrice').value) || 0;
                const shares = parseInt(settingsPanel.querySelector('#shares').value) || 0;

                // 将手数转换为股数
                saveStockSettings(code, {
                    costPrice,
                    shares: shares * 100 // 转换为股数
                });

                closeStockSettings();
                loadStockList();
                showAlert(`${name} 设置已保存`, 'info');
            });

            cancelBtn.addEventListener('click', closeStockSettings);

            return settingsPanel;
        }

        // 显示股票设置面板
        async function showStockSettings(code, name) {
            closeStockSettings(); // 先关闭可能存在的设置面板

            const settings = await getStockSettings(code);
            const settingsPanel = createStockSettingsPanel(code, name);
            document.body.appendChild(settingsPanel);

            // 填充现有设置，将股数转换为手数
            document.getElementById('costPrice').value = settings.costPrice || '';
            document.getElementById('shares').value = settings.shares ? (settings.shares / 100) : '';
        }

        // 关闭股票设置面板
        function closeStockSettings() {
            const settingsPanel = document.querySelector('.stock-settings-panel');
            if (settingsPanel) {
                settingsPanel.remove();
            }
        }

        // 检查止盈止损
        function checkPriceAlerts(stock, settings) {
            if (!settings.costPrice) return null;

            const currentPrice = stock.price;
            const profitPercent = ((currentPrice - settings.costPrice) / settings.costPrice * 100).toFixed(2);
            const now = Date.now();

            // 检查是否需要提醒
            if (settings.alertFrequency === 'once' && settings.lastAlertTime > 0) {
                return null;
            }

            if (settings.profitTarget && currentPrice >= settings.profitTarget) {
                // 更新最后提醒时间
                settings.lastAlertTime = now;

                return {
                    type: 'profit',
                    message: `${stock.name} 已达到止盈价 ${settings.profitTarget}，当前涨幅 ${profitPercent}%`
                };
            }

            if (settings.lossTarget && currentPrice <= settings.lossTarget) {
                // 更新最后提醒时间
                settings.lastAlertTime = now;

                return {
                    type: 'loss',
                    message: `${stock.name} 已达到止损价 ${settings.lossTarget}，当前跌幅 ${profitPercent}%`
                };
            }

            return null;
        }

        // 显示提醒
        function showAlert(message, type) {
            const alert = document.createElement('div');
            alert.className = `stock-alert ${type}`;

            // 添加图标
            const icon = document.createElement('span');
            icon.className = 'alert-icon';
            if (type === 'profit') {
                icon.innerHTML = '📈';
            } else if (type === 'loss') {
                icon.innerHTML = '📉';
            } else {
                icon.innerHTML = 'ℹ️';
            }

            // 添加消息
            const text = document.createElement('span');
            text.className = 'alert-message';
            text.textContent = message;

            // 添加关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.className = 'alert-close';
            closeBtn.innerHTML = '×';
            closeBtn.onclick = () => alert.remove();

            alert.appendChild(icon);
            alert.appendChild(text);
            alert.appendChild(closeBtn);

            document.body.appendChild(alert);

            // 5秒后自动关闭
            setTimeout(() => {
                alert.classList.add('fade-out');
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        }

        // 判断是否在交易时间内
        function isTradingTime() {
            const now = new Date();
            const hour = now.getHours();
            const minute = now.getMinutes();
            const day = now.getDay();

            // 周末休市
            if (day === 0 || day === 6) {
                return false;
            }

            // 上午交易时间 9:30-11:30
            if ((hour === 9 && minute >= 30) || (hour === 10) || (hour === 11 && minute <= 30)) {
                return true;
            }

            // 下午交易时间 13:00-15:00
            if ((hour === 13) || (hour === 14) || (hour === 15 && minute === 0)) {
                return true;
            }

            return false;
        }

        // 格式化时间
        function formatTime(date) {
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${hours}:${minutes}:${seconds}`;
        }

        // 格式化数字为逗号分隔法
        function formatNumber(num) {
            return num.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }

        // 显示设置面板
        function openSettings() {
            // 移除可能存在的旧面板
            closeSettings();

            // 创建遮罩层
            const overlay = document.createElement('div');
            overlay.className = 'settings-overlay active';
            overlay.onclick = closeSettings;
            document.body.appendChild(overlay);

            // 创建设置面板
            const settingsPanel = document.createElement('div');
            settingsPanel.className = 'settings-panel active';
            settingsPanel.innerHTML = `
                <div class="settings-content">
                    <h3>STOCK</h3>
                    <div class="stock-input">
                        <input type="text" id="stockCode" placeholder="输入6位股票代码" maxlength="6" autocomplete="off">
                        <button id="addStockBtn" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-primary/50 flex items-center gap-2 shadow-lg shadow-primary/20">
  <i class="fa fa-plus"></i> 添加股票
</button>
                        <button id="kimiAiBtn">KIMI AI</button>
                        <button id="importBtn">批量导入</button>
                        <div class="stock-summary">
                            <div class="summary-item">
                                <span class="summary-label">总成本</span>
                                <span class="summary-value" id="totalCost">0.00</span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">总盈利</span>
                                <span class="summary-value" id="totalProfit">0.00 <span class="summary-percent">0.00%</span></span>
                            </div>
                        </div>
                    </div>
                    <div class="refresh-status">
                        <span class="last-refresh">最后刷新：--:--:--</span>
                        <span class="market-status"></span>
                    </div>
                    <div id="stockList"></div>
                </div>
            `;

            // 先添加面板，再加载数据
            document.body.appendChild(settingsPanel);

            // 加载数据
            loadStockList();

            // 添加输入监听
            const input = settingsPanel.querySelector('#stockCode');
            const addButton = settingsPanel.querySelector('#addStockBtn');
            const importButton = settingsPanel.querySelector('#importBtn');

            // 限制只能输入数字
            input.addEventListener('input', (e) => {
                e.target.value = e.target.value.replace(/[^\d]/g, '');
            });

            // 按下回车键添加股票
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    addStock();
                }
            });

            // 输入框焦点事件，用于显示建议
            input.addEventListener('focus', async (e) => {
                if (e.target.value) {
                    stockSuggestions = await getStockSuggestions(e.target.value);
                    showSuggestions(stockSuggestions);
                }
            });

            // 输入框输入事件，用于更新建议
            input.addEventListener('input', async (e) => {
                stockSuggestions = await getStockSuggestions(e.target.value);
                currentSuggestionIndex = -1;
                showSuggestions(stockSuggestions);
            });

            // 输入框键盘事件，用于导航建议
            input.addEventListener('keydown', handleKeyNavigation);

            // 添加按钮点击事件
            addButton.addEventListener('click', () => addStock());

            // 批量导入按钮点击事件
            importButton.addEventListener('click', importStocks);

            // 输入框回车事件
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addStock();
                }
            });

            // 添加遮罩层点击事件
            overlay.addEventListener('click', (e) => {
                if (e.target === overlay) {
                    closeSettings();
                }
            });

            // 更新刷新状态
            updateRefreshStatus();

            // 初始化KIMI AI按钮
            initKimiAiButton();
        }

        // 关闭设置面板
        function closeSettings() {
            const settingsPanel = document.querySelector('.settings-panel');
            const overlay = document.querySelector('.settings-overlay');
            const suggestions = document.getElementById('stockSuggestions');

            if (settingsPanel) {
                settingsPanel.remove();
            }
            if (overlay) {
                overlay.remove();
            }
            if (suggestions) {
                suggestions.remove();
            }
        }

        // 初始化KIMI AI按钮
        function initKimiAiButton() {
            const kimiBtn = document.getElementById('kimiAiBtn');
            if (kimiBtn) {
                kimiBtn.addEventListener('click', () => {
                    showAlert('KIMI AI 功能即将上线，敬请期待！', 'info');
                });
            }
        }

        // 自动刷新相关变量
        let refreshTimer = null;
        let isClosedMarketRefreshed = false;

        // 开始自动刷新
        function startAutoRefresh() {
            stopAutoRefresh(); // 先停止可能存在的刷新
            isClosedMarketRefreshed = false; // 重置休市刷新标志

            refreshTimer = setInterval(async () => {
                if (isTradingTime()) {
                    const { stocks } = await getStoredStocks();
                    const stockData = await fetchStockData(stocks);
                    const stockList = document.getElementById('stockList');
                    if (stockList) {
                        loadStockList();
                    }
                    updateRefreshStatus();
                } else if (!isClosedMarketRefreshed) {
                    // 休市时只刷新一次
                    const { stocks } = await getStoredStocks();
                    const stockData = await fetchStockData(stocks);
                    const stockList = document.getElementById('stockList');
                    if (stockList) {
                        loadStockList();
                    }
                    updateRefreshStatus();
                    isClosedMarketRefreshed = true;
                }
            }, 2000); // 每2秒刷新一次
        }

        // 停止自动刷新
        function stopAutoRefresh() {
            if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;
            }
        }

        // 更新刷新状态
        function updateRefreshStatus() {
            const lastRefresh = document.querySelector('.last-refresh');
            const marketStatus = document.querySelector('.market-status');

            if (lastRefresh) {
                lastRefresh.textContent = `最后刷新：${formatTime(new Date())}`;
            }

            if (marketStatus) {
                if (isTradingTime()) {
                    marketStatus.textContent = '交易中';
                    marketStatus.className = 'market-status trading';
                } else {
                    marketStatus.textContent = '休市中';
                    marketStatus.className = 'market-status closed';
                    if (isClosedMarketRefreshed) {
                        marketStatus.textContent = '休市中（已更新）';
                    }
                }
            }
        }

        // 刷新股票数据
        async function refreshStockData() {
            if (!isTradingTime()) {
                showAlert('当前为休市时间，数据不会更新', 'info');
                return;
            }

            const { stocks } = await getStoredStocks();
            const stockData = await fetchStockData(stocks);
            const stockList = document.getElementById('stockList');
            if (stockList) {
                loadStockList();
            }
            updateRefreshStatus();
            showAlert('股票数据已更新', 'info');
        }

        // 初始化
        function init() {
            // 创建悬浮球
            const ball = createFloatingBall();

            // 加载股票列表
            loadStockList();

            // 开始自动刷新
            startAutoRefresh();
        }

        // 添加股票
        async function addStock() {
            try {
                const input = document.getElementById('stockCode');
                const code = input.value.trim();

                if (!code) {
                    alert('请输入股票代码');
                    return;
                }

                if (!validateStockCode(code)) {
                    alert('请输入6位数字股票代码');
                    return;
                }

                const prefix = getStockPrefix(code);
                if (!prefix) {
                    alert('不支持的股票代码格式');
                    return;
                }

                const fullCode = `${prefix}${code}`;
                const { stocks } = await getStoredStocks();

                if (!stocks.includes(fullCode)) {
                    const stockName = await getStockName(fullCode);
                    if (!stockName || stockName === fullCode) {
                        alert('无法获取股票信息，请检查股票代码是否正确');
                        return;
                    }

                    const newStocks = [...stocks, fullCode];
                    // 模拟chrome.storage.local.set
                    localStorage.setItem('stocks', JSON.stringify(newStocks));

                    // 清空输入框并保持焦点
                    input.value = '';
                    input.focus();

                    // 重新加载列表
                    loadStockList();

                    // 显示成功提示
                    showAlert(`已添加 ${stockName} 到您的观察列表`, 'info');
                } else {
                    alert('该股票已在列表中');
                }
            } catch (error) {
                console.error('添加股票失败:', error);
                alert('添加股票失败，请刷新页面后重试');
            }
        }

        // 加载股票列表
        async function loadStockList() {
            const stockList = document.getElementById('stockList');
            if (!stockList) return;

            const { stocks } = await getStoredStocks();
            const stockData = await fetchStockData(stocks);

            if (stocks.length === 0) {
                stockList.innerHTML = '<div class="stock-list-item">暂无股票，请添加</div>';
                return;
            }

            // 计算总成本和总盈利
            let totalCost = 0;
            let totalProfit = 0;

            stockData.forEach(stock => {
                if (stock.shares > 0) {
                    totalCost += stock.price * stock.shares;
                    totalProfit += stock.profitAmount;
                }
            });

            // 更新总成本和总盈利显示
            const totalCostElement = document.getElementById('totalCost');
            const totalProfitElement = document.getElementById('totalProfit');

            if (totalCostElement) {
                totalCostElement.textContent = formatNumber(totalCost);
            }

            if (totalProfitElement) {
                totalProfitElement.innerHTML = `${(totalProfit >= 0 ? '+' : '') + formatNumber(totalProfit)} <span class="summary-percent">${totalCost > 0 ? ((totalProfit / totalCost) * 100).toFixed(2) + '%' : '0.00%'}</span>`;
                totalProfitElement.className = `summary-value ${totalProfit > 0 ? 'profit' : (totalProfit < 0 ? 'loss' : '')}`;
            }

            // 将股票分为已设置持仓和未设置持仓两组
            const stocksWithPosition = stockData.filter(stock => stock.shares > 0);
            const stocksWithoutPosition = stockData.filter(stock => stock.shares === 0);

            // 对每组按涨幅倒序排序
            stocksWithPosition.sort((a, b) => parseFloat(b.changePercent) - parseFloat(a.changePercent));
            stocksWithoutPosition.sort((a, b) => parseFloat(b.changePercent) - parseFloat(a.changePercent));

            // 合并两组股票
            const sortedStockData = [...stocksWithPosition, ...stocksWithoutPosition];

            // 创建网格布局
            stockList.innerHTML = `
                <div class="stock-list-container">
                    ${sortedStockData.map(stock => {
                const priceChangeClass = stock.change > 0 ? 'up' : (stock.change < 0 ? 'down' : 'neutral');
                return generateStockCard(stock, priceChangeClass);
            }).join('')}
                </div>
            `;

            // 为每个股票的设置按钮添加事件
            document.querySelectorAll('.settings-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const code = btn.getAttribute('data-code');
                    const name = btn.getAttribute('data-name');
                    showStockSettings(code, name);
                });
            });

            // 为每个股票的删除按钮添加事件
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', async () => {
                    const code = btn.getAttribute('data-code');
                    const name = btn.getAttribute('data-name');

                    if (confirm(`确定要删除 ${name} 吗？`)) {
                        const { stocks } = await getStoredStocks();
                        const newStocks = stocks.filter(stockCode => stockCode !== code);

                        // 模拟chrome.storage.local.set
                        localStorage.setItem('stocks', JSON.stringify(newStocks));

                        // 重新加载列表
                        loadStockList();
                        showAlert(`${name} 已从观察列表中删除`, 'info');
                    }
                });
            });

            // 为每个股票的量化分析按钮添加事件
            document.querySelectorAll('.quant-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const code = btn.getAttribute('data-code');
                    const stock = sortedStockData.find(s => s.code === code);
                    if (stock && stock.quantitativeAnalysis) {
                        showQuantitativeAdvice(stock);
                    }
                });
            });
        }

        // 生成股票卡片
        function generateStockCard(stock, priceChangeClass) {
            // 获取量化分析结果
            const analysis = analyzeStock(stock);
            const actionClass = analysis.action;
            const actionIcon = getActionIcon(analysis.action);
            const actionText = getActionText(analysis.action);

            // 存储分析结果到股票对象中
            stock.quantitativeAnalysis = analysis;

            return `
                <div class="stock-list-item">
                    <div class="stock-info">
                        <div class="stock-header">
                            <div class="stock-name">
                                <strong>${stock.name}</strong>
                                <span class="stock-code">${stock.code}</span>
                            </div>
                            <div class="stock-actions">
                                <a href="javascript:void(0)" class="action-link detail-btn" onclick="window.open('https://quote.eastmoney.com/concept/${stock.code}.html')">详情</a>
                                <a href="javascript:void(0)" class="action-link settings-btn" data-code="${stock.code}" data-name="${stock.name}">设置</a>
                                <a href="javascript:void(0)" class="action-link delete-btn" data-code="${stock.code}" data-name="${stock.name}">删除</a>
                                <a href="javascript:void(0)" class="action-link quant-btn" data-code="${stock.code}">量化</a>
                            </div>
                        </div>
                        <div class="stock-price ${priceChangeClass}">
                            ${formatNumber(stock.price)}
                            <span class="stock-change">${stock.change > 0 ? '+' : ''}${formatNumber(stock.change)} (${stock.changePercent}%)</span>
                            <span class="quant-indicator ${actionClass}">${actionIcon} ${actionText}</span>
                        </div>
                        <div class="stock-details">
                            <div class="detail-item">成交量: ${formatNumber(stock.volume)}</div>
                            <div class="detail-item">成交额: ${formatNumber(stock.amount)}</div>
                        </div>
                        ${stock.shares > 0 ? `
                            <div class="profit-info ${stock.profitAmount > 0 ? 'up' : (stock.profitAmount < 0 ? 'down' : '')}">
                                持仓盈亏: ${stock.profitAmount > 0 ? '+' : ''}${formatNumber(stock.profitAmount)} (${stock.profitPercent}%)
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;
        }

        // 分析股票并给出建议
        function analyzeStock(stock) {
            // 简单的量化分析逻辑
            const changePercent = parseFloat(stock.changePercent);

            // 基于涨跌幅给出建议
            if (changePercent > 2) {
                return {
                    action: 'sell',
                    confidence: 75,
                    reasons: [
                        `短期涨幅较大，达到${changePercent}%`,
                        '可能面临获利回吐压力',
                        '技术指标显示超买'
                    ]
                };
            } else if (changePercent < -2) {
                return {
                    action: 'buy',
                    confidence: 70,
                    reasons: [
                        `短期跌幅较大，达到${changePercent}%`,
                        '可能存在反弹机会',
                        '技术指标显示超卖'
                    ]
                };
            } else {
                return {
                    action: 'hold',
                    confidence: 60,
                    reasons: [
                        '价格波动较小',
                        '市场情绪平稳',
                        '等待明确信号'
                    ]
                };
            }
        }

        // 获取建议图标
        function getActionIcon(action) {
            switch (action) {
                case 'buy': return '📈';
                case 'sell': return '📉';
                case 'hold': return '⏸️';
                default: return '❓';
            }
        }

        // 获取建议文本
        function getActionText(action) {
            switch (action) {
                case 'buy': return '买入';
                case 'sell': return '卖出';
                case 'hold': return '持有';
                default: return '未知';
            }
        }

        // 显示量化分析建议
        function showQuantitativeAdvice(stock) {
            const analysis = stock.quantitativeAnalysis;
            if (!analysis) return;

            // 创建分析面板
            const panel = document.createElement('div');
            panel.className = 'quantitative-advice-panel active';
            panel.innerHTML = `
                <div class="advice-content">
                    <h3>${stock.name} (${stock.code}) 量化分析</h3>
                    <div class="advice-action ${analysis.action}">
                        <span class="action-icon">${getActionIcon(analysis.action)}</span>
                        <span class="action-text">${getActionText(analysis.action)}</span>
                        <span class="confidence">可信度: ${analysis.confidence}%</span>
                    </div>
                    <div class="advice-message">
                        基于当前市场数据和技术指标分析，我们对${stock.name}给出${getActionText(analysis.action)}建议。
                    </div>
                    <div class="advice-reasons">
                        <h4>分析依据：</h4>
                        <ul>
                            ${analysis.reasons.map(reason => `<li>${reason}</li>`).join('')}
                        </ul>
                    </div>
                    <div class="advice-details">
                        <div>当前价格: ${formatNumber(stock.price)}</div>
                        <div>涨跌幅: ${stock.changePercent}%</div>
                        <div>成交量: ${formatNumber(stock.volume)}</div>
                        <div>成交额: ${formatNumber(stock.amount)}</div>
                    </div>
                    <div class="advice-actions">
                        <button class="close-btn" onclick="closeQuantitativeAdvice()">关闭</button>
                    </div>
                </div>
            `;

            document.body.appendChild(panel);
        }

        // 关闭量化分析建议面板
        function closeQuantitativeAdvice() {
            const panel = document.querySelector('.quantitative-advice-panel');
            if (panel) {
                panel.remove();
            }
        }

        // 页面加载完成后初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', init);
        } else {
            init();
        }
    </script>